


// jQuery(window).load(function() {
//
//     "use strict";
//
//     // Page Preloader
//     jQuery('#preloader').delay(350).fadeOut(function(){
//         jQuery('body').delay(350).css({'overflow':'visible'});
//     });
// });

jQuery(document).ready(function() {
    // $('#preloader').delay(350).fadeOut();
    "use strict";

    var browserIdentify =function () {
        var browser = {
            versions: function () {
                var u = navigator.userAgent, app = navigator.appVersion;
                return {         //移动终端浏览器版本信息
                    trident: u.indexOf('Trident') > -1, //IE内核
                    presto: u.indexOf('Presto') > -1, //opera内核
                    webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                    gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
                    mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                    android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
                    iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
                    iPad: u.indexOf('iPad') > -1, //是否iPad
                    webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
                };
            }(),
            language: (navigator.browserLanguage || navigator.language).toLowerCase()
        }

        if (browser.versions.mobile) {//判断是否是移动设备打开。browser代码在下面
            var ua = navigator.userAgent.toLowerCase();//获取判断用的对象
            /*if (ua.match(/MicroMessenger/i) == "micromessenger") {

            }*/
            // $("#mobilelogout").show()
            $("#overview , #member ,#bonus,#dividend,#finance,#system,#menutoggle,#pclogout,#verification").show()
        } else {
            $("#overview , #member ,#bonus,#dividend,#finance,#system,#menutoggle,#pclogout,#verification").show()

            if(browser.versions.trident){
                $.rootErrorDialog("您的浏览器不兼容,请安装火狐浏览器",2000,function () {
                    window.location.href="/admin/404.html"
                });
            }
        }
    }

    browserIdentify()


    $("#refresh").on("click",function () {
        window.location.reload();
    })

    // Toggle Left Menu
    jQuery('.leftpanel .nav-parent > a').on('click', function() {

        var parent = jQuery(this).parent();
        var sub = parent.find('> ul');
        // Dropdown works only when leftpanel is not collapsed
        if(!jQuery('body').hasClass('leftpanel-collapsed')) {
            if(sub.is(':visible')) {
                sub.slideUp(200, function(){
                    parent.removeClass('nav-active');
                    jQuery('.mainpanel').css({height: ''});
                    adjustmainpanelheight();
                });
            } else {
                closeVisibleSubMenu(parent.siblings(".nav-parent"));
                parent.addClass(' nav-active ');
                sub.slideDown(200, function(){
                    adjustmainpanelheight();
                });
            }
        }
        return false;
    });



    function adjustmainpanelheight() {
        // Adjust mainpanel height
        var docHeight = jQuery(document).height();
        if(docHeight > jQuery('.mainpanel').height())
            jQuery('.mainpanel').height(docHeight);
    }
    adjustmainpanelheight();


    // Tooltip
    jQuery('.tooltips').tooltip({ container: 'body'});

    // Popover
    jQuery('.popovers').popover();

    // Close Button in Panels
    jQuery('.panel .panel-close').click(function(){
        jQuery(this).closest('.panel').fadeOut(200);
        return false;
    });

    // Form Toggles
    //jQuery('.toggle').toggles({on: true});

    //jQuery('.toggle-chat1').toggles({on: false});

    var scColor1 = '#428BCA';
    if (jQuery.cookie('change-skin') && jQuery.cookie('change-skin') == 'bluenav') {
        scColor1 = '#fff';
    }




    // Minimize Button in Panels
    jQuery('.minimize').click(function(e){
        e.preventDefault();
        var t = jQuery(this);
        var p = t.closest('.panel');
        if(!jQuery(this).hasClass('maximize')) {
            p.find('.panel-body, .panel-footer').slideUp(200);
            t.addClass('maximize');
            t.html('&plus;');
        } else {
            p.find('.panel-body, .panel-footer').slideDown(200);
            t.removeClass('maximize');
            t.html('&minus;');
        }
        return false;
    });


    // Add class everytime a mouse pointer hover over it
    jQuery('.nav-bracket > li').hover(function(){
        jQuery(this).addClass('nav-hover');
    }, function(){
        jQuery(this).removeClass('nav-hover');
    });


    // Menu Toggle
    jQuery('.menutoggle').click(function(){

        var body = jQuery('body');
        var bodypos = body.css('position');

        if(bodypos != 'relative') {

            if(!body.hasClass('leftpanel-collapsed')) {
                body.addClass('leftpanel-collapsed');
                jQuery('.nav-bracket ul').attr('style','');

                jQuery(this).addClass('menu-collapsed');

            } else {
                body.removeClass('leftpanel-collapsed chat-view');
                jQuery('.nav-bracket li.active ul').css({display: 'block'});

                jQuery(this).removeClass('menu-collapsed');

            }
        } else {

            if(body.hasClass('leftpanel-show'))
                body.removeClass('leftpanel-show');
            else
                body.addClass('leftpanel-show');

            adjustmainpanelheight();
        }

    });

    // Chat View
    jQuery('#chatview').click(function(){

        var body = jQuery('body');
        var bodypos = body.css('position');

        if(bodypos != 'relative') {

            if(!body.hasClass('chat-view')) {
                body.addClass('leftpanel-collapsed chat-view');
                jQuery('.nav-bracket ul').attr('style','');

            } else {

                body.removeClass('chat-view');

                if(!jQuery('.menutoggle').hasClass('menu-collapsed')) {
                    jQuery('body').removeClass('leftpanel-collapsed');
                    jQuery('.nav-bracket li.active ul').css({display: 'block'});
                } else {

                }
            }

        } else {

            if(!body.hasClass('chat-relative-view')) {

                body.addClass('chat-relative-view');
                body.css({left: ''});

            } else {
                body.removeClass('chat-relative-view');
            }
        }

    });

    reposition_topnav();
    reposition_searchform();

    jQuery(window).resize(function(){

        if(jQuery('body').css('position') == 'relative') {

            jQuery('body').removeClass('leftpanel-collapsed chat-view');

        } else {

            jQuery('body').removeClass('chat-relative-view');
            jQuery('body').css({left: '', marginRight: ''});
        }


        reposition_searchform();
        reposition_topnav();

    });



    /* This function will reposition search form to the left panel when viewed
     * in screens smaller than 767px and will return to top when viewed higher
     * than 767px
     */
    function reposition_searchform() {
        if(jQuery('.searchform').css('position') == 'relative') {
            jQuery('.searchform').insertBefore('.leftpanelinner .userlogged');
        } else {
            jQuery('.searchform').insertBefore('.header-right');
        }
    }



    /* This function allows top navigation menu to move to left navigation menu
     * when viewed in screens lower than 1024px and will move it back when viewed
     * higher than 1024px
     */
    function reposition_topnav() {
        if(jQuery('.nav-horizontal').length > 0) {

            // top navigation move to left nav
            // .nav-horizontal will set position to relative when viewed in screen below 1024
            if(jQuery('.nav-horizontal').css('position') == 'relative') {

                if(jQuery('.leftpanel .nav-bracket').length == 2) {
                    jQuery('.nav-horizontal').insertAfter('.nav-bracket:eq(1)');
                } else {
                    // only add to bottom if .nav-horizontal is not yet in the left panel
                    if(jQuery('.leftpanel .nav-horizontal').length == 0)
                        jQuery('.nav-horizontal').appendTo('.leftpanelinner');
                }

                jQuery('.nav-horizontal').css({display: 'block'})
                    .addClass('nav-pills nav-stacked nav-bracket');

                jQuery('.nav-horizontal .children').removeClass('dropdown-menu');
                jQuery('.nav-horizontal > li').each(function() {

                    jQuery(this).removeClass('open');
                    jQuery(this).find('a').removeAttr('class');
                    jQuery(this).find('a').removeAttr('data-toggle');

                });

                if(jQuery('.nav-horizontal li:last-child').has('form')) {
                    jQuery('.nav-horizontal li:last-child form').addClass('searchform').appendTo('.topnav');
                    jQuery('.nav-horizontal li:last-child').hide();
                }

            } else {
                // move nav only when .nav-horizontal is currently from leftpanel
                // that is viewed from screen size above 1024
                if(jQuery('.leftpanel .nav-horizontal').length > 0) {

                    jQuery('.nav-horizontal').removeClass('nav-pills nav-stacked nav-bracket')
                        .appendTo('.topnav');
                    jQuery('.nav-horizontal .children').addClass('dropdown-menu').removeAttr('style');
                    jQuery('.nav-horizontal li:last-child').show();
                    jQuery('.searchform').removeClass('searchform').appendTo('.nav-horizontal li:last-child .dropdown-menu');
                    jQuery('.nav-horizontal > li > a').each(function() {

                        jQuery(this).parent().removeClass('nav-active');

                        if(jQuery(this).parent().find('.dropdown-menu').length > 0) {
                            jQuery(this).attr('class','dropdown-toggle');
                            jQuery(this).attr('data-toggle','dropdown');
                        }

                    });
                }

            }

        }
    }


    // Sticky Header
    if(jQuery.cookie('sticky-header'))
        jQuery('body').addClass('stickyheader');

    // Sticky Left Panel
    if(jQuery.cookie('sticky-leftpanel')) {
        jQuery('body').addClass('stickyheader');
        jQuery('.leftpanel').addClass('sticky-leftpanel');
    }

    // Left Panel Collapsed
    if(jQuery.cookie('leftpanel-collapsed')) {
        jQuery('body').addClass('leftpanel-collapsed');
        jQuery('.menutoggle').addClass('menu-collapsed');
    }

    // Changing Skin
    var c = jQuery.cookie('change-skin');
    var cssSkin = 'css/style.'+c+'.css';
    if (jQuery('body').css('direction') == 'rtl') {
        cssSkin = '../css/style.'+c+'.css';
        jQuery('html').addClass('rtl');
    }
    if(c) {
        jQuery('head').append('<link id="skinswitch" rel="stylesheet" href="'+cssSkin+'" />');
    }

    // Changing Font
    var fnt = jQuery.cookie('change-font');
    if(fnt) {
        jQuery('head').append('<link id="fontswitch" rel="stylesheet" href="css/font.'+fnt+'.css" />');
    }

    // Check if leftpanel is collapsed
    if(jQuery('body').hasClass('leftpanel-collapsed'))
        jQuery('.nav-bracket .children').css({display: ''});


    // Handles form inside of dropdown
    jQuery('.dropdown-menu').find('form').click(function (e) {
        e.stopPropagation();
    });


    // This is not actually changing color of btn-primary
    // This is like you are changing it to use btn-orange instead of btn-primary
    // This is for demo purposes only
    var c = jQuery.cookie('change-skin');
    if (c && c == 'greyjoy') {
        $('.btn-primary').removeClass('btn-primary').addClass('btn-orange');
        $('.rdio-primary').addClass('rdio-default').removeClass('rdio-primary');
        $('.text-primary').removeClass('text-primary').addClass('text-orange');
    }


    //路由
    function closeVisibleSubMenu (navMeun) {

        navMeun.each(function() {
            var t = jQuery(this);
            if(t.children('ul').length) {

                t.children('ul').slideUp(200,function () {
                    t.removeClass('active nav-active');

                })
            }else{
                t.removeClass('active nav-active');

            }
        });
    }
    //根会员
    var rootUser=$("#root-user");
    var authority ={
        "1":"[注册用户] ",
        "2":"[vip] ",
        "3":"[房间所有者] ",
        "4":"[超级管理员] "
    };


    var navActive =function (href,tier) {
        // alert("navActive")
        var body = jQuery('body');
        var href = "#"+href;
           var  $a = $("#main-meun").find('a[href|="'+ href +'"]'),
            $li=$a.parent("li"),
         $navMeun = $a.parents(".nav-meun").siblings(".nav-meun");
        closeVisibleSubMenu($navMeun);
        $(".leftpanel .nav-parent .children li").removeClass("active");
        switch (tier){
            case 1:
                $li.addClass("active");
                break;
            case 2:
                if(!body.hasClass('leftpanel-collapsed')) {
                    $li.parent("ul").slideDown(200,function () {
                        $li.addClass("active").parents(".nav-parent").addClass("active nav-active")
                    });
                }else{
                    $li.addClass("active").parents(".nav-parent").addClass("active nav-active")
                }
                break;
        }
    };
    var doGetUser = function (callback) {
        $.restPost("/user/doGetUserInfo",{token:window.localStorage.getItem('token')}).done(function (msg,data) {
            //记录登录 包括权限
            // console.log(msg,data)
            console.log(data)
            rootUser.text(data.userName)
            window.localStorage.setItem('userId',data.id)
            window.localStorage.setItem('userName',data.userName)

            callback(4)
        })
        .fail(function (msg,data) {
            window.location.href="/admin/login_page.html"
        })
        // callback(4)
    };
    var to404=function () {
        // alert("to404")
        window.location.href="/admin/404.html"
    };

    var TplToContentpanel=function (_href,_url,_title ,tier) {
        $('#preloader').show()
        //关闭所有层
        layer.closeAll();

        var $contentpanel=$("#contentpanel");
        var $titleTag=$("#title-tag");
        //登录状态

        doGetUser(function(authority) {
            // console.log(authority)

            $.get(_url).done(function (tpl) {
                // console.log(tpl)
                navActive(_href,tier);
                $titleTag.text(_title);
                $contentpanel.html(tpl);
                $("body").removeClass("leftpanel-show")
                $('#preloader').delay(350).fadeOut();

            })


        });


    };

    //退出
    var logout = function () {
        $.restPost("/user/doLogout",{
            token:window.localStorage.getItem('token'),
        }).done(function (msg,data) {
            window.location.href="/admin/login_page.html"
        }).fail(function (msg,data) {
            //跳回登录界面
           alert("注销失败")
        })
    };
    $("#logout , #mobilelogout").on("click",function () {
        logout()
    });
   function routesMapInit() {
       var nd= $.now()

       var routes = {
           '/article.html':function () { TplToContentpanel('/article.html','/admin/pages/article.html?n='+nd,'文章管理',1) },
           '/article-page/:id':function () { TplToContentpanel('/article-page.html','/admin/pages/article-page.html?n='+nd,'文章详情',1) },
           '/type.html':function () { TplToContentpanel('/type.html','/admin/pages/type.html?n='+nd,'类型管理',1) },
       };

       var router = Router(routes);
       router.init();

   }
    routesMapInit()

    // routesMap()






});

